package org.xiaojinlong.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * Created by jinlong on 2015/4/12.
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.connect(new InetSocketAddress("127.0.0.1", 5432));
        channel.register(selector, SelectionKey.OP_CONNECT);
        while (true) {
            // 每个SelectionKey对应了注册的一个通道
            Set<SelectionKey> keys = selector.selectedKeys();
            for (SelectionKey key: keys) {
                if (key.isConnectable()) {
                    // 由于非阻塞模式 connect只管发起连接请求 finishConnect()方法会
                    // 阻塞到链接结束并返回是否成功
                    // 还有一个isConnectionPending()返回的是是否处于连接状态（还在三次握手中））
                    if (channel.finishConnect()) {
                        key.interestOps(SelectionKey.OP_READ);
                    }
                }
            }
        }
    }
}
